import React, { useCallback, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Button, Col, Form, Icon, Input, message, Spin, Tooltip } from 'antd';
import { getZoomeyeSearchConfig, postZoomeyeSearchConfig } from '@api/system';
import lodash from 'lodash';
import './index.less';
import { bindActionCreators } from 'redux';
import { actions as orgManageActions } from '@containers/asset-org-manage/reducer';
import { connect } from 'react-redux';
import { CIDR_RE, IP_RE, URL_RE } from '@util/constants';

const formItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 20
  }
};

const prefixCls = 'search-config-tab';

const SearchConfigTab = props => {
  const [loading, setLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const { closeModal, updateImmediately, form, setState, initError } = props;
  const { validateFields } = form;

  useEffect(() => {
    setLoading(true);
    getZoomeyeSearchConfig().then(res => {
      const search = lodash.get(res, 'data.data.config.search', {});
      const title = lodash.get(search, 'title', '');
      const ssl = lodash.get(search, 'ssl', '');
      let ip = lodash.get(search, 'ip', []);
      let site = lodash.get(search, 'site', []);

      //处理返回字段可能为null
      ip = ip ? ip.join('\n') : '';
      site = site ? site.join('\n') : '';

      form.setFieldsValue({ title, ssl, ip, site }, () => {
        setLoading(false);
      });
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSubmit = useCallback(
    type => {
      validateFields((err, values) => {
        if (err) {
          return;
        }
        const { ip, title, ssl, site } = values;

        if (!ip && !title && !ssl && !site) {
          setErrorMessage('请至少输入一个搜索条件进行搜索');
          return;
        }

        const search = {
          title,
          ssl
        };

        if (site) {
          const siteArr = site
            .split('\n')
            .filter(Boolean)
            .map(item => item.trim());
          const checked = siteArr.some(item => !URL_RE.test(item));
          if (checked) {
            setErrorMessage('填写的域名格式错误');
            return;
          }
          search.site = siteArr;
        }
        if (ip) {
          const ipArr = ip
            .split('\n')
            .filter(Boolean)
            .map(item => item.trim());
          const checked = ipArr.some(item => !IP_RE.test(item) && !CIDR_RE.test(item));
          if (checked) {
            setErrorMessage('填写的IP格式错误');
            return;
          }
          search.ip = ipArr;
        }

        setLoading(true);
        postZoomeyeSearchConfig({
          search: lodash.pickBy(search, i => i)
        })
          .then(() => {
            setLoading(false);
            if (type === 'update') {
              updateImmediately(false);
            } else {
              message.success('保存成功');
            }
            if (initError) {
              setState({ initError: false });
            }
            closeModal();
          })
          .catch(() => {
            message.error('设置失败');
            setLoading(false);
          });
      });
    },
    [updateImmediately, closeModal, validateFields, initError, setState]
  );

  return (
    <Spin spinning={loading} className={prefixCls}>
      <div className={`${prefixCls}-title`}>
        <div className={`${prefixCls}-title`}>
          <Icon type="info-circle" />
          将根据填写的不同搜索条件在zoomeye.org上进行“或”查询，查询结果会根据资产是否在资产管理列表来更新到“未在资产列表”或者“已在资产列表”。
        </div>
      </div>
      <Form layout="horizontal" {...formItemLayout} className={`${prefixCls}-form`}>
        <Form.Item label="域名" colon={false}>
          {form.getFieldDecorator('site')(
            <Input.TextArea
              placeholder="请输入域名，多个域名用换行符分隔"
              style={{ width: '80%' }}
            />
          )}
        </Form.Item>
        <Form.Item label="IP段" colon={false}>
          {form.getFieldDecorator('ip')(
            <Input.TextArea
              placeholder="请输入网段，例如52.2.254.36/24,多个网段用换行符分隔"
              style={{ width: '80%' }}
            />
          )}
        </Form.Item>
        <Form.Item label="网站标题" colon={false}>
          {form.getFieldDecorator('title')(<Input placeholder="请输入网站标题的关键词" />)}
        </Form.Item>
        <Form.Item
          label={
            <span className="ssl-label">
              ssl
              <Tooltip title="可通过产品名或公司名称搜索对应目标">
                <Icon type="info-circle" />
              </Tooltip>
            </span>
          }
          colon={false}
        >
          {form.getFieldDecorator('ssl')(<Input placeholder="请输入ssl的关键词" />)}
        </Form.Item>
        <Col span={18} offset={6}>
          <div className="error-message">{errorMessage}</div>
        </Col>
        <Form.Item />
      </Form>
      <div className="config-btn-group">
        <Button onClick={closeModal}>取&nbsp;&nbsp;消</Button>
        <Button onClick={() => handleSubmit('')}>保&nbsp;&nbsp;存</Button>
        <Button type="primary" onClick={() => handleSubmit('update')}>
          保存并查询
        </Button>
      </div>
    </Spin>
  );
};

SearchConfigTab.propTypes = {
  visible: PropTypes.bool,
  initError: PropTypes.bool,
  setState: PropTypes.func,
  closeModal: PropTypes.func,
  updateImmediately: PropTypes.func,
  form: PropTypes.object
};

const mapStateToProps = state => {
  return {
    initError: lodash.get(state, 'orgManage.initError', false)
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(orgManageActions, dispatch)
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create()(SearchConfigTab));
